package com.kuangxiaoyang.foodapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.UUID;

public class RegisterActivity extends AppCompatActivity {

    private EditText phoneEtRg;
    private EditText pwdEtRg;
    private Button cancelBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initEvent();
    }

    private void initView() {
        phoneEtRg = findViewById(R.id.phone_et_rg);
        pwdEtRg = findViewById(R.id.pwd_et_rg);
        cancelBtn = findViewById(R.id.cancel_btn);
    }

    public void register(View view) {
        final String phone = phoneEtRg.getText().toString();
        final String password = pwdEtRg.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = UrlUtil.basePath + "/regist";
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("name", UUID.randomUUID().toString().substring(1, 5));  //随机生成一个用户名
                    jsonObject.put("telephone", phone);
                    jsonObject.put("password", password);

                    JSONObject jsonObject1 = new JSONObject(GainDataUtil.gainDataForPost(url, jsonObject));
                    final boolean success = jsonObject1.getBoolean("success");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (success) {
                                //如果注册成功跳转至登录页
                                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                toMainActivity();
                            } else {
                                Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //跳转到登录页
    public void toMainActivity() {
        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
        startActivity(intent);
    }

    private void initEvent() {
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
}